package com.tuuzed.android.sample.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.google.zxing.Result
import com.tuuzed.android.base.BaseActivity
import com.tuuzed.android.dialog.DialogBuilderProxy
import com.tuuzed.android.qrcode.CaptureCallback
import com.tuuzed.android.qrcode.CaptureFragment
import com.tuuzed.android.qrcode.QRCodeUtil
import com.tuuzed.android.sample.R
import com.tuuzed.android.sample.util.BeepManager
import com.tuuzed.android.util.ActivityUtil
import com.tuuzed.android.utilkt.toastShort
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions

class CaptureActivity : BaseActivity() {
    private lateinit var mBeepManager: BeepManager
    private lateinit var mCaptureFragment: CaptureFragment
    override fun isHomeAsUpEnabled(): Boolean = true
    override fun isSwipeBackEnable(): Boolean = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.capture_act)
        mBeepManager = BeepManager(this)
        setSupportActionBar(findViewById(R.id.toolbar))
        attachCaptureFragment()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.capture_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null && resultCode == Activity.RESULT_OK && requestCode == RC_OPEN_ALBUM) {
            val dialog = DialogBuilderProxy.newProxy(this)
                    .cancelable(false)
                    .progressBar("正在扫描...")
                    .show(supportFragmentManager)
            QRCodeUtil.handleChoiceQRCodePic(this, data) {
                handleResult(it)
                dialog.dismiss()
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }


    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item!!.itemId) {
            R.id.action_open_album -> {
                openAlbum()
                return true
            }
            R.id.action_open_or_close_lamp -> {
                mCaptureFragment.torchState = !mCaptureFragment.torchState
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }


    override fun onDestroy() {
        super.onDestroy()
        mBeepManager.close()
    }


    @AfterPermissionGranted(RC_REQUEST_CAMERA_PERM)
    private fun attachCaptureFragment() {
        if (EasyPermissions.hasPermissions(this, CAMERA_PERM)) {
            mCaptureFragment = CaptureFragment.newInstance()
            mCaptureFragment.setCaptureCallback(object : CaptureCallback {
                override fun onResult(result: Result) {
                    handleResult(result)
                }

                override fun onCameraError(t: Throwable) {

                }
            })
            ActivityUtil.replaceSupportFragmentTo(supportFragmentManager, R.id.fl_content, mCaptureFragment)
        } else {
            EasyPermissions.requestPermissions(this, "扫描二维码，需要获取摄像头权限。", RC_REQUEST_CAMERA_PERM, CAMERA_PERM)
        }

    }

    @AfterPermissionGranted(RC_READ_EXTERNAL_STORAGE_PERM)
    private fun openAlbum() {
        if (EasyPermissions.hasPermissions(this, READ_EXTERNAL_STORAGE_PERM)) {
            QRCodeUtil.choiceQRCodePic(this, "选择二维码图片", RC_OPEN_ALBUM)
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this,
                    "识别相册中的二维码图片，需要获取读取手机存储权限。",
                    RC_READ_EXTERNAL_STORAGE_PERM, READ_EXTERNAL_STORAGE_PERM)
        }
    }

    private fun handleResult(result: Result?) {
        if (result != null) {
            mBeepManager.playBeepSoundAndVibrate()
            val intent = Intent()
            intent.putExtra(EXTRA_KEY_SCAN_RESULT, result.text)
            setResult(android.app.Activity.RESULT_OK, intent)
            toastShort(result.text)
            mCaptureFragment.rescan()
//            finish()
        } else {
            toastShort("识别失败")
        }
    }

    companion object {
        private const val RC_OPEN_ALBUM = 1000
        private const val RC_REQUEST_CAMERA_PERM = 1001
        private const val RC_READ_EXTERNAL_STORAGE_PERM = 1002
        private const val CAMERA_PERM = Manifest.permission.CAMERA
        private const val READ_EXTERNAL_STORAGE_PERM = Manifest.permission.READ_EXTERNAL_STORAGE
        const val EXTRA_KEY_SCAN_RESULT = "text"
    }

}
